(function() {
	var $ = require(L('$')), _ = require(L('_'));

	var popup = {};
	popup.modal = function(child) {
		var ui = $.layout('popup/modal');
		$.touch(ui.wrapper, function() {
			ui.win.close();
		});
		$.touch(ui.icon_close, function() {
			ui.win.close();
		});
		ui.child.add(child);
		ui.win.display = function(callBack) {
			ui.win.open();
			$.tap(ui.btnAccept, function() {
				ui.win.close();
				callBack && callBack();
			});
		};
		return ui.win;
	};
	popup.terms_and_conditions = function() {
		var ui = $.layout('popup/t&c');
		ui.win = popup.modal(ui.view);
		$.tap(ui.btnCancel, function() {
			ui.win.close();
		});
		ui.content.html = $.getStaticContent().TermsAndConditions;
		var loaded = false;
		$.webview.onload(ui.content, function() {
			$.webview.css(ui.content, 'pageTitle', 'display', 'none');
			$.webview.css(ui.content, 'tcBigTitle', 'display', 'block');
			$.webview.css(ui.content, 'content', 'border', '0px');
			$.webview.css(ui.content, 'content', 'padding', '0 0 0 10px');
			$.webview.css(ui.content, 'content', 'width', '240px');
			$.webview.css(ui.content, 'content', 'fontSize', '15px');
			$.opacity_show(ui.content);
			loaded = true;
		});
		_.delay(function() {
			if (!loaded)
				ui.content.html = $.getStaticContent().TermsAndConditions;
		}, 200)
		ui.win.display = function(callBack) {
			ui.win.open();
			$.tap(ui.btnAccept, function() {
				ui.win.close();
				callBack && callBack();
			});
		};
		return ui.win;
	};
	popup.share = function(data, callBack) {
		var ui = $.layout('popup/share');
		ui.win = popup.modal(ui.view);
		if (data.pinterest == null) {
			ui.view.remove(ui.btnSharePinterest);
			ui.view.height = 145;
		} else {
			$.tap(ui.btnSharePinterest, function() {
				ui.win.close();
				share.pinterest(data.pinterest);
				callBack && callBack($.enum('share').Pinterest);
			});
		}
		$.tap(ui.btnShareFacebook, function() {
			ui.win.close();
			popup.facebook_friends(data.fb, callBack).ShowFirstPage();
		});
		$.tap(ui.btnShareTwitter, function() {
			ui.win.close();
			share.twitter(data.twitter);
			callBack && callBack($.enum('share').Twitter);
		});
		$.tap(ui.btnShareEmail, function() {
			ui.win.close();
			popup.share_email(data.email, callBack).display();
		});
		return ui.win;
	};
	popup.share_email = function(data, callBack) {
		var ui = $.layout('popup/share_email');
		var emailAddress = $.currentUserEmailAddress();
		if (!$.isNull(emailAddress)) {
			ui.txtSender.value = emailAddress;
			ui.txtSender.enabled = false;
		}
		ui.txtRecipient.setAutocapitalization(Ti.UI.TEXT_AUTOCAPITALIZATION_NONE);
		ui.win = popup.modal(ui.view);
		ui.win.display = function(callBack) {
			ui.win.open();
		};
		$.tap(ui.btnSubmit, function() {
			var senderEmail = ui.txtSender.value, recipientEmails = ui.txtRecipient.value, error = '', valid = true;
			recipientEmails = $.trim(recipientEmails).replace(/ /g, "\,");
			var splitedRecipientEmails = recipientEmails.split(',');
			var numberEmailToSend = 0;
			if ($.isNull(recipientEmails)) {
				valid = false;
				error = 'Please enter your friend\'s email address.';
			} else {
				for (var i = 0, j = splitedRecipientEmails.length; i < j; i++) {
					var email = splitedRecipientEmails[i];
					email = $.trim(email);
					if (!$.isNull(email) && !$.isValidEmail(email))
						valid = false;
					else {
						if (!$.isNull(email))
							numberEmailToSend++;
					}
				}
				if (!valid) {
					error = "One of your email addresses is invalid, please try again.";
				} else if (numberEmailToSend > 3) {
					valid = false;
					error = "You can enter only three email addresses, please try again.";
				} else if ($.isNull(senderEmail)) {
					valid = false;
					error = "Sender email is invalid.";
				}
			}
			if (!valid) {
				$.a(error, L('message_share_error_title'));
				return;
			}
			ui.win.close();
			$.mask();
			if (data.desireID) {
				$.webservice().shareUGDViaEmail(data.desireID, senderEmail, recipientEmails, function(e) {
					var result = JSON.parse(e);
					if (result.Success) {
						$.a(L('ugd_share_success'), L('ugd_success_title'));
						callBack && callBack($.enum('share').Email);
					} else
						$.a(result.Message, L('message_share_error_title'));
					$.mask(false);
				});
			} else {
				$.webservice().shareViaEmail(senderEmail, recipientEmails, data.productVariantID, data.retailerStoreID, data.coreProductVariantID, data.notificationID, function(e) {
					var result = JSON.parse(e);
					if (result.Success) {
						$.a(result.Message, L('message_share_success_title'));
						callBack && callBack($.enum('share').Email);
					} else
						$.a(result.Message, L('message_share_error_title'));
					$.mask(false);
				});
			}
		});
		return ui.win;
	};

	popup_data = {};
	popup_data.selectedFbUIDs = new Array();
	popup.facebook_friends = function(shareData, callBack) {
		popup_data.selectedFbUIDs = new Array();
		var ui = $.layout('popup/facebook_friends');
		ui.win = popup.modal(ui.view);
		var top = 10, left = 10, offset = 0, limit = 50;
		ui.selectedIDs = new Array();
		ui.load_friends = function(offset, limit) {
			$.mask();
			$.facebook().login(function(e) {
				$.facebook().getFriends(offset, limit, function(e) {
					var friends = new Array();
					if (e && e.result)
						friends = JSON.parse(e.result).data;
					if (friends.length < limit)
						ui.btnMore.opacity = 0;
					for (var i = 0, j = friends.length; i < j; i++) {
						ui.container.add(popup.facebook_friend(friends[i], top, left));
						var index = ((i % 2) + 2) % 2;
						left = index == 0 ? 142 : 10;
						if (index == 1)
							top += 130;
					}
					if (offset == 0)
						ui.win.open();
					$.mask(false);
				});
			});
		};
		ui.win.ShowFirstPage = function() {
			ui.load_friends(offset, limit);
		};
		$.tap(ui.btnMore, function() {
			offset += limit;
			ui.load_friends(offset, limit);
		});
		$.tap(ui.btnSubmit, function() {
			if (popup_data.selectedFbUIDs.length == 0) {
				$.a('Please select at least one friend before submit.', 'Sorry');
				return;
			}
			$.mask();
			$.facebook().post_to_friends(popup_data.selectedFbUIDs, shareData, function(e) {
				$.mask(false);
				ui.win.close();
				callBack && callBack($.enum('share').Facebook);
			});
		});
		return ui.win;
	};
	popup.facebook_friend = function(data, top, left) {
		var pui = $.layout('popup/partial/facebook_friend');
		pui.view.top = top;
		pui.view.left = left;
		$.cache_image(data.pic_square, pui.pic_square);
		pui.friendName.text = data.name;
		$.touch(pui.view, function() {
			if (pui.btnCheck.backgroundImage == L('btn_check')) {
				pui.view.backgroundColor = '#fff4dd';
				pui.btnCheck.backgroundImage = L('btn_check_on');
				popup_data.selectedFbUIDs.push(pui.view.uid);
			} else {
				pui.view.backgroundColor = '#fff';
				pui.btnCheck.backgroundImage = L('btn_check');
				popup_data.selectedFbUIDs.pop(pui.view.uid);
			}
		});
		pui.view.uid = data.uid;
		return pui.view;
	};

	popup.enter_suburb = function(callBack) {
		var ui = $.layout('popup/enter_suburb');
		ui.win = popup.modal(ui.view);
		$.tap(ui.btnSubmit, function() {
			var suburb = ui.txtSuburb.value;
			if ($.isNull(suburb))
				$.a(L('err_popup_suburb_require'), L('message_error_title'));
			else {
				ui.win.close();
				callBack && callBack(suburb);
			}
		});
		return ui.win;
	};

	var share = {};
	share.pinterest = function(data) {
		data.description = $.encode_uri(data.description);
		var pinURL = String.format('http://pinterest.com/pin/create/button/?url=%s&media=%s&description=%s', data.link, data.picture, data.description);
		Ti.Platform.openURL(pinURL);
	};
	share.twitter = function(data) {
		if (!$.isNull(data.message)) {
			if (data.message.length > 139)
				data.message = data.message.substring(0, 139);
			data.message = $.encode_uri(data.message);
			var link = 'http://twitter.com/share?text=' + data.message;
			Ti.Platform.openURL(link);
		}
	};

	module.exports = popup;
})();
